import axios from "axios";
import type {
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from "axios";
import crypto from "crypto-js";
import { errorCodeType } from "./error-code";
const server = axios.create({
  //配置的跨域标识
  baseURL: import.meta.env.BASE_URL,
  //超时
  timeout: 5000,
});

//请求拦截
server.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Token = token;
    }
    return config;
  },
  (error: AxiosError) => {
    console.log(error, "e");
  }
);

//响应拦截
server.interceptors.response.use(
  (config: AxiosResponse) => {
    const code = config.data["code"] || 200;
    if (code == 200) {
      return Promise.resolve(config.data);
    } else {
      // 响应错误信息
      const msg = errorCodeType(code);
      return Promise.reject(config.data);
    }
  },
  (error: AxiosError) => {
    console.log(error);
  }
);
/** 请求配置参数 */
interface configApi {
  /** 请求参数 */
  data?: object;
  /** 配置请求头 */
  headers?: object;
  [key: string]: any;
}

function http(type: string = "get", url: string, options: configApi) {
  const { data, headers } = options;
  let config: AxiosRequestConfig = {
    url: url,
    method: type,
  };
  if (type == "get") {
    config.params = { ...data };
  } else if (type == "post") {
    // const dataAes = crypto.AES.encrypt('vaule', 'key', { mode: crypto.mode.ECB, padding: crypto.pad.Pkcs7 }).toString()
    // console.log('加密：', dataAes)
    // const data = crypto.enc.Utf8.stringify(crypto.AES.decrypt(dataAes, 'key',)).toString()
    // console.log('解密：', data)
    config.data = data;
  }
  if (headers) {
    config.headers = headers;
  }
  return server(config);
}
/** 二次封装后的axios */
export default class AxiosModul {
  /** 发送get请求 */
  static get(
    url: string,
    data: { [key: string]: any } = { data: {}, headers: {} }
  ) {
    return http("get", url, data);
  }
  /** 发送post请求 */
  static post(
    url: string,
    data: { [key: string]: any } = { data: {}, headers: {} }
  ) {
    return http("post", url, data);
  }
}
